package com.atguigu.gmall.product.service;

import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author: 李旭
 * @Time: 14:16
 * @Description:
 */
@Service
public class TestServiceImpl implements TestService {

    @Autowired
    private RedisTemplate redisTemplate;//
    @Autowired
    private RedissonClient redissonClient;

    @Override
    public void testLock() {
        RLock lock = redissonClient.getLock("lock");
        lock.lock();
        //1:获取值
        Integer num = (Integer) redisTemplate.opsForValue().get("num");
        //2：值 ++
        num++;
        //3:设置值
        redisTemplate.opsForValue().set("num",num);
        lock.unlock();
    }

    //private final ReentrantLock lock = new ReentrantLock();
    //分布式锁
/*    @Override
    public void testLock() {

        //lock.lock();  //1 : true     0:false
        Boolean lock = redisTemplate.opsForValue().setIfAbsent("lock", 0);
        if(lock){
            //获取到了锁   0  5000
            //1:获取值
            Integer num = (Integer) redisTemplate.opsForValue().get("num");
            //2：值 ++
            num++;
            //3:设置值
            redisTemplate.opsForValue().set("num",num);

            redisTemplate.delete("lock");
        }else {
            //未获取到锁
            testLock();
        }
    }*/
}
